package org.eclipseuseradmin.ui.editors;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.swt.SWT;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipseuseradmin.internal.ui.UserAdminUiPlugin;
import org.eclipseuseradmin.internal.ui.editors.RoleElementInput;
import org.eclipseuseradmin.ui.model.RoleElementModel;
import org.eclipseuseradmin.ui.utils.EditorSupport;
import org.osgi.service.useradmin.UserAdmin;

public abstract class BaseRoleElementEditor extends FormEditor implements
		IEditorActionBarContributor {

	private EditorSupport editorSupport;

	protected RoleElementModel model;

	public BaseRoleElementEditor() {
		editorSupport = new EditorSupport(this);
	}

	public EditorSupport getEditorSupport() {
		return editorSupport;
	}

	public RoleElementInput getRoleElementInput() {
		return (RoleElementInput) getEditorInput();
	}

	public RoleElementModel getModel() {
		if (model == null) {
			model = new RoleElementModel(getUserAdmin(), getRoleElementInput()
					.getRoleElement());
		}
		return model;
	}

	public UserAdmin getUserAdmin() {
		return UserAdminUiPlugin.getUserAdmin();
	}

	@Override
	public void doSave(IProgressMonitor monitor) {

		if (editorSupport.isError()) {
			openSaveErrorDialog("error on page", new Status(IStatus.ERROR,
					UserAdminUiPlugin.PLUGIN_ID, "error"));
			return;
		}

		commitPages(true);
		getModel().save();

		editorSupport.setDirty(false);
	}

	@Override
	public boolean isDirty() {
		return editorSupport.isDirty();
	}

	@Override
	public void doSaveAs() {
	}

	@Override
	public boolean isSaveAsAllowed() {
		return false;
	}

	private void openSaveErrorDialog(String error, IStatus status) {

		ErrorDialog dialog = new ErrorDialog(getContainer().getShell(),
				"Save Error", error, status, SWT.NONE);
		dialog.open();
	}

	@Override
	public void init(IEditorSite site, IEditorInput input)
			throws PartInitException {

		super.init(site, input);
	}

	public void init(IActionBars bars, IWorkbenchPage page) {
		// TODO Auto-generated method stub

	}

}
